import {cbs} from '../../../config/settings.js';
import io from 'socket.io-client';
import {mapGetters} from 'vuex';
import Tips from '../Tips/';
import Messages from '../Messages/';

let socket;


module.exports = {
    name: 'head-nav',
    data() {
        return {
            dialogVisible: false,
            audio: null,
            tts: null
        }
    },
    methods: {
        /**
         * 退出确认
         */
         logoutTip(fn=() =>{}, errFn=err => {}) {
            this.$confirm('你确定退出登录么?', '确认退出', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(fn, errFn);
         },
        /**
         * 退出登录
         */
         logoutDir() {
            this.$$api_user_logout(null, res => {
                if(res.event === 0) {
                    socket && socket.close();
                    this.$store.dispatch('remove_userinfo').then(() => {
                        this.$router.push('/login');
                    });
                }else {
                    cbs.submitError.call(this, `退出失败`);
                }
            })
         },
        /**
         * 确认 + 退出登录
         */
        logout() {
            this.logoutTip(this.logoutDir, err => {});
        },
        /**
         * 弹出框-退出/修改账号密码
         * @param {string} cmditem 弹框类型
         */
        setDialogInfo(cmditem) {
            if (!cmditem) {
                this.$message('菜单选项缺少command属性');
                return;
            }
            switch (cmditem) {
                case 'out':
                    this.logout();
                    break;
                case 'modify':
                    this.$router.push('/account/modifyPwd/account')
                    break;
            }
        },
        /**
         * 前往首页
         */
        goHome() {
            this.$router.push('/index');
        },
        /**
         * 重复登录
         */
        duplicateLogin() {
            this.$store.dispatch('remove_userinfo').then(() => {
                this.$router.push('/login');
            });
        },
        /**
         * 新订单提醒
         */
        hasNewOrder(id, count=0) {
            const h = this.$createElement;
            // message提醒
            this.$message({
                showClose: true,
                message: h('p', null, [
                    h('tips', {
                        props: {
                            text: `您有${count}条待处理新订单`
                        },
                        on: {
                            check: () => {
                                this.$router.push('/order/new-list');
                            }
                        }
                    })
                ])
            })

            // 更新新订单总数
            this.$store.dispatch('update_new_orders', count);

            // this.getSingleNewOrder(id);
        },
        /**
         * 获取单个新订单
         */
        getSingleNewOrder(id) {
            let data = this.$$formData({
                waterStoreOrderFinishId: id
            });

            this.$$api_order_oneNewList(data, res => {
                if(res.event === 0) {
                    this.$store.dispatch('insert_new_list', {
                            item: res.obj,
                            size: 5
                        });
                }else {
                    cbs.submitError.call(this, ` ${res.msg}`);
                }
            })
        },
        /**
         * 空桶订单提醒
         */
        hasConOrder(id, count=0) {
            const h = this.$createElement;
            this.$message({
                showClose: true,
                message: h('p', null, [
                    h('tips', {
                        props: {
                            text: `您有${count}条待确认空桶订单`
                        },
                        on: {
                            check: () => {
                                this.$router.push('/order/empty-barrel');
                            }
                        }
                    })
                ])
            })

            this.$store.dispatch('update_empty_barrel_orders', count);
        },
        /** 
         * 获取空桶订单总数
         */
        getEmptyBarrelOrdersTotal() {
            this.$$api_order_emptyBarrelTotal(null, res => {
                if(res.event === 0) {
                    this.$store.dispatch('update_empty_barrel_orders', res.obj);
                }else {
                    cbs.submitError.call(this, `获取空桶订单总数失败，${res.msg}`);
                }
            })
        },
        /** 
         * 获取新订单总数
         */
        getNewOrdersTotal() {
            let data = this.$$formData({
                pageNum: 1,
                size: 5
            })

            this.$$api_order_newList(data, res => {
                if(res.event === 0) {
                    this.$store.dispatch('update_new_orders', res.maxCount);
                }else {
                    cbs.submitError.call(this, `获取新订单总数失败，${res.msg}`);
                }
            })
        },
        /** 
         * 跳转至订单
         */
        turnToOrder(cmditem) {
            if(!cmditem) {
                this.$message('菜单选项缺少command属性');
                return;
            }
            switch(cmditem) {
                case 'news':
                    // let txt = '/static/tip.mp3';
                    // this.audio.src=txt;
                    // this.audio.play()
                    this.$router.push('/order/new-list');
                    break;
                case 'emptyBarrel':
                    this.$router.push('/order/empty-barrel');
                    break;
                case 'deposite':
                    this.$router.push('/order/deposit');
                    break;
            }
        },
        /** 
         * 上传商品结果通知
         */
        getInfo(id) {
            let data = this.$$formData({
                waterStoreMessageId: id
            })
            this.$$api_home_getMessage(data, res => {
                if(res.event === 0) {
                    this.$message({
                        showClose: true,
                        message: h('p', null, [
                            h('tips', {
                                props: {
                                    text: `${res.obj.message}`
                                }
                            })
                        ])
                    })
                }
            })
        },
        /** 
         * 押金订单提示
         */
        getDeposit(count, flag) {
            const h = this.$createElement;
            flag && this.$message({
                showClose: true,
                message: h('p', null, [
                    h('tips', {
                        props: {
                            text: `您有${count}条待确认押金订单`
                        },
                        on: {
                            check: () => {
                                this.$router.push('/order/deposit');
                            }
                        }
                    })
                ])
            })

            this.$store.dispatch('update_deposite_orders', count);
        },
        /**
         * 获取不在线时的消息
         */
        onGetMessages() {
            var a = [{
                title: 1,
                message: 'sdf'
            }, {
                title: 2,
                message: 'sdf'
            }]

            this.$$api_user_getMessage(null, res => {
                if(res.event === 0) {
                    this.showMessage(res.obj, 0, res.obj.length);
                }
            })
        },
        /**
         * 展示不在线时的消息
         */
        showMessage(arr, i, len) {
            if(i < len) {
                this.$alert(arr[i].message, arr[i].title, {
                    confirmButtonText: '确定',
                    callback: action => {
                        this.showMessage(arr, ++i, len)
                    }
                })
            }
        },
        /**
         * 获取用户未处理押金订单数量
         */
        getUserDepositCount(data) {
            return new Promise((resolve, reject) => {
                this.$$api_order_userDepositOrders(data, res => {
                    if(res.event === 0) {
                        // return res.maxCount
                         resolve(res.maxCount)
                    }else {
                        // return 0;
                        resolve(0);
                    }
                }, {
                    tokenFlag: true
                })
            })
        },
        /**
         * 获取送水工未处理押金订单数量
         */
        getDeliverDepositCount(data) {
            return new Promise((resolve, reject) => {
                this.$$api_order_deliverDepositOrders(data, res => {
                    if(res.event === 0) {
                        // return res.maxCount
                        resolve(res.maxCount)
                    }else {
                        // return 0;
                        resolve(0);
                    }
                }, {
                    tokenFlag: true
                })
            })
        },
        /**
         * 获取总的未处理押金订单数量
         */
        onDepositCount() {
            let data = this.$$formData({
                requestPage: 1,
                pageSize: 1,
                status: 0,
                token: this.$store.state.user.userinfo.token,
                waterStoreId: this.$store.state.user.userinfo.uid
            });

            let p1 = this.getUserDepositCount(data)
                        .catch(() => 0);
            let p2 = this.getDeliverDepositCount(data)
                        .catch(() => 0);

            Promise.all([p1, p2])
                .then(([user, deliver]) => {
                    this.getDeposit(user + deliver, false);
                })
        },
        /**
         * 创建Audio
         */
        createAudio() {
            this.audio = new Audio();
        },
    },
    computed: {
        total() {
            return this.$store.state.global.newOrders + this.$store.state.global.emptyBarrelOrders + this.$store.state.global.depositeOrders;
        },
        ...mapGetters({
            token: 'getToken',
            waterId: 'getUserId',
            newOrders: 'getNewOrders',
            emptyBarrel: 'getEmptyBarrelOrders',
            deposite: 'getDepositeOrders'
        }),
        global() {
            return this.$store.state.global;
        },
    },
    created() {
        this.getEmptyBarrelOrdersTotal();
        this.getNewOrdersTotal();
        this.onDepositCount();
        this.onGetMessages();
        this.createAudio();

        let url = `ws://172.18.92.153:9094?socketAuthorizationU=${this.waterId}&socketAuthorizationT=${this.token}`;

        socket = io(url);
        socket.on('connect', () => {
            console.log('connect')
            socket.emit('feidi_connect_message', this.waterId, this.token, '1001');
        })
        let num = 2;

        socket.on('reconnect_error', (error) => {
            var reg = new RegExp(this.$store.state.user.userinfo.token);
            if(!reg.test(url)) {
                socket.close();
                url = `ws://172.18.92.153:9094?socketAuthorizationU=${this.waterId}&socketAuthorizationT=${this.token}`;
                socket = io(url);
            }
        })

        socket.on('disconnect', () => {
            console.log('disconnect')
            socket.close();
        });

        socket.on('feidi_receiver_message', (id, ...data) => {
            console.log(id)
            console.log(data)
            switch(id) {
                    case 1001:
                        this.dialogVisible = true;
                        break;
                    case 1003:
                        this.hasNewOrder(...data);
                        break;
                    case 1004:
                        this.hasConOrder(...data);
                        break;
                    case 1005:
                    case 1006:
                    case 1007:
                        this.getInfo(data);
                        break;
                    case 1008:
                    case 1009:
                        this.getDeposit(this.deposite + 1);
                        break;
                }
        })
    },
    components: {
        Tips,
        Messages
    }
}